package com.pand.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

/**
 * Created by lh on 2017/11/8.
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryOracle", transactionManagerRef = "transactionManagerOracle", basePackages = {"com.pand.service"})
public class RepositoryOracleConfig {
    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    @Qualifier("oracleDS")
    private DataSource OracleDS;

    @Bean(name = "entityManagerOracle")
    @Primary
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryOracle(builder).getObject().createEntityManager();
    }

    @Bean(name = "entityManagerFactoryOracle")
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryOracle(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(OracleDS)
                .properties(getVendorProperties(OracleDS))
                .packages("com.pand.model") //设置实体类所在位置
                .persistenceUnit("OraclePersistenceUnit")
                .build();
    }

    private Map<String, String> getVendorProperties(DataSource dataSource) {
        Map map =  jpaProperties.getHibernateProperties(dataSource);
        map.put("hibernate.dialect","org.hibernate.dialect.Oracle10gDialect");
        return map;
    }

    @Bean(name = "transactionManagerOracle")
    @Primary
    PlatformTransactionManager transactionManagerOracle(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryOracle(builder).getObject());
    }
}
